<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/3/21
 * Time: 9:18
 */

namespace app\api\controller;


use think\Db;

class Login extends Base
{
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone：填写的手机号
     * return:  0    输入手机号/手机号格式不正确/验证码发送不成功/操作数据库失败
     *          1    非法来源
     *          200  发送成功
     * type   调用的场景   1 注册    2 找回密码
     */
    public function getPhoneCode()
    {
        $params = input('param.');
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $params['phone'])) {
            return json(['status' => 0, 'msg' => '手机号格式不正确']);
        }
        // 注册判断手机号是否已存在
        if(isset($params['type']) && $params['type'] == 1){
            $haved = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
            if($haved){
                return json(['status' => 0, 'msg' => '此手机号已注册']);
            }
        }
        // 重置密码判断手机号是否存在
        if(isset($params['type']) && $params['type'] == 2){
            $haved = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
            if(!$haved){
                return json(['status' => 0, 'msg' => '输入的手机号不存在']);
            }
        }
        $send_num = Db::table('up_phonecode')->where('phone', $params['phone'])->value('send_num');
        if($send_num >= 10){
            return json(['status' => 0, 'msg' => '同一账号一天最多发送10次']);
        }
        // 防盗刷
        $time = $_SERVER['HTTP_REQDATE'];
        $reqKey = $_SERVER['HTTP_REQKEY'];
        $appId = "A6070308312682";
        $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
        $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
        if($myreqKey != $reqKey){
            return json(['status'=>1,'msg'=>'非法来源']);
        }
        
        $code = GetRandCode(); //6位数验证码
//        $code = 111111; //6位数验证码
        $sendres = YzxSms($code, $params['phone'], ''); //发送验证码
        
        if($sendres['code'] != '00000') { //发送不成功
            return json(['status' => 0, 'msg' => $sendres['msg']]);
        } else {
            $isHave = Db::table('up_phonecode')->where('phone', $params['phone'])->find();
            $data = [
                'code' => $code, // 验证码
                'time' => time(), // 验证码发送的时间戳
                'date_time' => date('Y-m-d H:i:s') // 日期格式
            ];
            if(empty($isHave)){ // 第一次发送 插入
                $data['phone'] = $params['phone'];
                $res = Db::table('up_phonecode')->insert($data);
            }else{ // 更新
                $data['status'] = 0;
                $data['send_num']  = $isHave['send_num'] + 1;
                $res = Db::table('up_phonecode')->where('phone', $params['phone'])->update($data);
            }
            
            if($res) {
                return json(['status' => 200, 'msg' => $code]);
            }else{
                return json(['status' => 0, 'msg' => '数据库操作失败']);
            }
        }
    }
    
    /**
     * 用户注册
     * @return \think\response\Json
     * phone    手机号
     * code     验证码
     * password 密码
     */
    public function register(){
        $params = input('param.');
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if(trim($params['code'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        if(trim($params['password'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入密码']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $params['phone'])) {
            return json(['status' => 0, 'msg' => '手机号格式不正确']);
        }
        $user = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(!empty($user)){
            return json(['status' => 0, 'msg' => '该手机号已注册']);
        }
        //验证验证码
        $res = Db::table('up_phonecode')->where('phone', $params['phone'])->find();
        if($params['code'] != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        $data = [
            'user_phone' => $params['phone'],
            'user_password' => md5($params['password']),
            'user_token' => md5(date('YmdHis') . rand(100000, 999999)),
            'user_last_time' => date('Y-m-d H:i:s'),
            'user_time' => date('Y-m-d H:i:s')
        ];
    
        Db::startTrans();
        try{
            // 插入用户
            Db::table('up_u_user')->insert($data);
            // 修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            
            Db::commit();
            $result = 1;
        }catch(\Exception $e){
            Db::rollback();
            $result = 2;
        }
        if($result == 1){
            $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '注册失败']);
        }
    }
    
    /**
     * 账号密码登录
     * @return \think\response\Json
     * phone       手机号
     * password    密码
     */
    public function passwordLogin(){
        $phone = input('phone');
        $password = input('password');
        if(trim($phone, ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if(trim($password, ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入密码']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '手机号格式不正确']);
        }
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($user)){
            return json(['status' => 0, 'msg' => '该手机号尚未注册']);
        }
        if($user){
            if(md5($password) != $user['user_password']){
                return json(['status' => 0, 'msg' => '密码错误']);
            }
            if($user['user_status'] == 2){
                return json(['status' => 0, 'msg' => '该用户已被冻结，请联系管理员']);
            }
            // TODO:缺少用户被删除的判断
        }
        
        $update = [
            'user_token' => md5(date('YmdHis') . rand(100000, 999999)),
            'user_last_time' => date('Y-m-d H:i:s'),
            'user_is_first' => 2
        ];
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        if($res){
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 200, 'msg' => '登录失败']);
        }
    }
    
    /**
     * 找回密码
     * @return \think\response\Json
     * phone         手机号
     * code          验证码
     * new_passowrd  新密码
     */
    public function resetPassword(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $new_password = trim(input('new_password'), ' ');
        if($phone == ''){
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if($code == ''){
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        if($new_password == ''){
            return json(['status' => 0, 'msg' => '请输入新密码']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '手机号格式不正确']);
        }
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($user)){
            return json(['status' => 0, 'msg' => '该手机号尚未注册']);
        }
        //验证验证码
        $res = Db::table('up_phonecode')->where('phone', $phone)->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        $update = [
            'user_password' => md5($new_password),
            'user_update_time' => date('Y-m-d H:i:s')
        ];
        $result = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        if($result){
            // 修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            return json(['status' => 200, 'msg' => '重置密码成功']);
        }else{
            return json(['status' => 0, 'msg' => '重置密码失败']);
        }
    }
    
    /**
     * 用户登录/注册
     * @return \think\response\Json
     * phone        手机号
     * code         验证码
     */
    public function userLogin(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        
        if($phone == '' || $code == '') {
            return json(['status' => 0, 'msg' => '有未填项，请检查']);
        }
        //验证手机号
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        //验证验证码
        $res = Db::table('up_phonecode')->where('phone', $phone)->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        $isHave = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if($isHave){
            if($isHave['user_status'] == 2){
                return json(['status' => 0, 'msg' => '该账号已被冻结']);
            }
            if($isHave['user_status'] == 3){
                return json(['status' => 0, 'msg' => '该账号已被删除']);
            }
        }
        
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_token'] = $token;
        $data['user_last_time'] = date('Y-m-d H:i:s');
        
        Db::startTrans();
        try{
            if($isHave){ // 登录
                $data['user_is_first'] = 2;
                Db::table('up_u_user')->where('user_phone', $phone)->update($data);
            }else{ // 注册&登录
                $data['user_phone'] = $phone;
                $data['user_time'] = date('Y-m-d H:i:s');
                Db::table('up_u_user')->insert($data);
            }
            // 修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            Db::commit();
            $result = 1;
        }catch(\Exception $e){
            Db::rollback();
            $result = 2;
        }
        
        if($result == 1){
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }
    
    /**
     * 第三方登录/注册
     * @return \think\response\Json
     * thirdToken   微信token
     */
    public function thirdLogin(){
        $user_wx_token = input('thirdToken');
        
        $isHave = Db::table('up_u_user')->where('user_wx_token', $user_wx_token)->find();
        
        if($isHave) { // 如果登录过
            if($isHave['user_status'] == 2) {
                return json(['status' => 0, 'msg' => '该账号已被冻结']);
            }
            if($isHave['user_status'] == 3) {
                return json(['status' => 0, 'msg' => '该账号已被删除']);
            }
            if($isHave['user_phone']){ // 如果已绑定手机号,直接登录
                $token = md5(date('YmdHis') . rand(100000, 999999));
                $data['user_token'] = $token;
                $data['user_last_time'] = date('Y-m-d H:i:s');
                $res = Db::table('up_u_user')->where('user_wx_token', $user_wx_token)->update($data);
                if($res){
                    $info = Db::table('up_u_user')->where('user_wx_token', $user_wx_token)->find();
                    $rytoken = $this->rongyun($info['user_id'],'who',$info['user_image']);
                    $info['rytoken'] = $rytoken['token'];
                    return json(['status' => 200, 'msg' => $info]);
                }else{
                    return json(['status' => 0, 'msg' => '登录失败']);
                }
            }else{
                return json(['status' => 300, 'msg' => '您未曾绑定手机号，建议您先绑定']);
            }
        }else{
            return json(['status' => 300, 'msg' => '第一次登录，去登录']);
        }
    }
    
    /**
     * 绑定手机号
     * @return \think\response\Json
     * phone        手机号
     * code         验证码
     * thirdToken   微信token
     * thirdName    微信昵称
     * thirdImg     微信头像
     */
    public function binding(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $user_wx_token = input('thirdToken');
        $user_wx_nickname = input('thirdName');
        $user_wx_image = input('thirdImg');
    
        if($phone == '' || $code == '') {
            return json(['status' => 0, 'msg' => '有未填项，请检查']);
        }
        //验证手机号
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        //验证验证码
        $res = Db::table('up_phonecode')->where('phone', $phone)->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        $isHave = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if($isHave){
            if($isHave['user_status'] == 2){
                return json(['status' => 0, 'msg' => '该账号已被冻结']);
            }
            if($isHave['user_status'] == 3){
                return json(['status' => 0, 'msg' => '该账号已被删除']);
            }
            if($isHave['user_wx_token'] == $user_wx_token){
                return json(['status' => 0, 'msg' => '该手机号已绑定其它微信']);
            }
        }
    
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_token'] = $token;
        $data['user_last_time'] = date('Y-m-d H:i:s');
        $data['user_wx_token'] = $user_wx_token;
        $data['user_wx_nickname'] = $user_wx_nickname;
        $data['user_wx_image'] = $user_wx_image;
    
        Db::startTrans();
        try{
            if($isHave){ // 登录
                $data['user_is_first'] = 2;
                Db::table('up_u_user')->where('user_phone', $phone)->update($data);
            }else{ // 注册&登录
                $data['user_phone'] = $phone;
                $data['user_time'] = date('Y-m-d H:i:s');
                Db::table('up_u_user')->insert($data);
            }
            // 修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            Db::commit();
            $res = 1;
        }catch(\Exception $e){
            Db::rollback();
            $res = 2;
        }
    
        if($res == 1){
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $info['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }
    
    /**
     * 获取省市区的三维数组
     * @return \think\response\Json
     */
    public function getArea()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }elseif($res == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
        
        $provinceLists = Db::name('area')->where('level', 1)->select();//省
        $cityLists = Db::name('area')->where('level', 2)->select();//市
        $districtLists = Db::name('area')->where('level', 3)->select();//区
        foreach($cityLists as $k => $city) {
            foreach($districtLists as $kk => $district) {
                if($city['district_id'] == $district['pid']) {
                    $cityLists[$k]['qu'][] = $district;
                }
            }
        }
        foreach($provinceLists as $key => $province) {
            foreach($cityLists as $ke => $city) {
                if($province['district_id'] == $city['pid']) {
                    $provinceLists[$key]['city'][] = $city;
                }
            }
        }
        return json(['status' => 200, 'msg' => $provinceLists]);
        
    }
    
    /**
     * 平台用户使用协议
     * @return \think\response\Json
     */
    public function useAgreement(){
        $agreement = Db::table('up_about')->where('about_id', 2)->value('about_content');
        return json(['status' => 200, 'msg' => $agreement]);
    }
}